package com.yingpai.fitness.dvp_2_0.main.fragment.dynamic;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.yingpai.fitness.R;
import com.yingpai.fitness.dvp_2_0.common.adapter.BaseAdapterHelper;
import com.yingpai.fitness.dvp_2_0.common.adapter.QuickAdapter;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.callback.Callback;
import com.yingpai.fitness.dvp_2_0.common.finalokgo.request.RequestType;
import com.yingpai.fitness.dvp_2_0.common.fragment.CommonFragment;
import com.yingpai.fitness.dvp_2_0.common.util.SharedPreferencesHelp;
import com.yingpai.fitness.dvp_2_0.common.util.constant.Contacts;
import com.yingpai.fitness.dvp_2_0.main.activity.dynamic.DynamicDetailActivity;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Constant;
import com.yingpai.fitness.dvp_2_0.main.util.constant.Url;
import com.yingpai.fitness.entity.dynamic.DynamicListBean;
import com.yingpai.fitness.entity.wx.TokenBean;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * 动态--关注模块
 */
public class AttentionDynamicFragment extends CommonFragment implements OnRefreshLoadMoreListener {

    private Unbinder unbinder;
    private TokenBean token;
    @BindView(R.id.xgrid)
    ListView xgrid;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.title_bar)
    RelativeLayout title_bar;
    @BindView(R.id.empty)
    LinearLayout empty;
    private int pageNum = 1;
    private int pageSize = 5;

    public static AttentionDynamicFragment getInstance() {
        return new AttentionDynamicFragment();
    }

    private QuickAdapter<DynamicListBean.MapBean.PageInfoBean.ListBean> adapter;

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dvp_2_0_attentiondynameic, container, false);
        unbinder = ButterKnife.bind(this, view);
        title_bar.setVisibility(View.GONE);
        refreshLayout.setOnRefreshLoadMoreListener(this);
        refreshLayout.setRefreshHeader(new MaterialHeader(context).setColorSchemeResources(R.color.common_color));
        EventBus.getDefault().register(this);
        token = (TokenBean) SharedPreferencesHelp.getBean(Constant.TOKENBEAN);

        adapter = new QuickAdapter<DynamicListBean.MapBean.PageInfoBean.ListBean>(context, R.layout.dynamic_followed_list_item) {
            @Override
            protected void convert(BaseAdapterHelper helper, final DynamicListBean.MapBean.PageInfoBean.ListBean item) {
                /**
                 * 用户头像
                 */
                CircleImageView dynamic_follow_user_head_iv = helper.getView(R.id.dynamic_followed_user_head_iv);
                Glide.with(context).load(item.getPublisherPhotoUrl()).error(R.mipmap.icon_user_default).into(dynamic_follow_user_head_iv);
                /**
                 * 用户名称
                 */
                TextView
                        dynamic_follow_user_name = helper.getView(R.id.dynamic_followed_user_name);
                dynamic_follow_user_name.setText(item.getPublisherName() != null ? item.getPublisherName() : "");
                /**
                 * 日期
                 */
                TextView dynamic_follow_date_tv = helper.getView(R.id.dynamic_follow_date_tv);
                dynamic_follow_date_tv.setText(item.getPublishTime() != null ? item.getPublishTime() + "" : "");
                /**
                 * 简介内容
                 */
                TextView follow_brief_tv_content = helper.getView(R.id.follow_brief_tv_content);
                follow_brief_tv_content.setText(
                        item.getThemeTitle() != null ?
                                item.getThemeTitle() : "简介内容为空");
                /**
                 * 简介图片
                 */
                ImageView follow_brief_iv_content = helper.getView(R.id.follow_brief_iv_content);

                Glide.with(context).load(item.getPhotoUrl()).error(R.mipmap.default_big_bg).into(follow_brief_iv_content);
                /**
                 * 位置
                 */
                TextView followed_user_location = helper.getView(R.id.followed_user_location);
                followed_user_location.setText(item.getPublishLocale() != null ? item.getPublishLocale() : "位置内容为空");
                /**
                 * 喜欢/收藏
                 */
                TextView followed_user_collect_tv = helper.getView(R.id.followed_user_collect_tv);
                followed_user_collect_tv.setText(item.getPraiseNo() != 0 ? item.getPraiseNo() + "" : "0");
                ImageView follow_user_like_iv = helper.getView(R.id.follow_user_like_iv);
                if (item.getIsPraised() == 0) {
                    follow_user_like_iv.setImageResource(R.mipmap.bbs_like_no);
                } else {
                    follow_user_like_iv.setImageResource(R.mipmap.bbs_like);
                }
            }
        };
        xgrid.setAdapter(adapter);

        xgrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Bundle bundle = new Bundle();
                bundle.putInt("id", adapter.getItem(position).getId());
                bundle.putInt("isPraised", adapter.getItem(position).getIsPraised());
                startActivity(DynamicDetailActivity.class, bundle);
            }
        });

        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void initData() {
        showDialog(context, null);
        HttpParams httpParams = new HttpParams();
        httpParams.put("customerId", token.getId());
        httpParams.put("pageNum", pageNum++);
        httpParams.put("pageSize", pageSize);
        finalOkGo.request(RequestType.POST, Contacts.HOST_SERVER + Url.GET_DYNAMIC_FOLLOW, httpParams, Url.GET_DYNAMIC_FOLLOW,
                new Callback<DynamicListBean>() {
                    @Override
                    public void onSuccess(DynamicListBean bean) {
                        if (Constant.REQUEST_SUCCESS.equals(bean.getResult())) {
                            if (!"查询成功，暂无数据".equals(bean.getMsg()) && !"查询失败".equals(bean.getMsg())) {
                                if (pageNum - 1 == 1) {
                                    if (bean.getMap().getPageInfo().getTotal() > 0) {
                                        empty.setVisibility(View.GONE);
                                        adapter.clear();
                                        adapter.addAll(bean.getMap().getPageInfo().getList());
                                    } else {
                                        empty.setVisibility(View.VISIBLE);
                                    }
                                } else {
                                    adapter.addAll(bean.getMap().getPageInfo().getList());
                                }
                                refreshLayout.finishRefresh();
                                refreshLayout.finishLoadMore();
                                adapter.notifyDataSetChanged();

                                int pagecount;
                                if (bean.getMap().getPageInfo().getTotal() % pageSize == 0) {
                                    pagecount = bean.getMap().getPageInfo().getTotal() / pageSize;
                                } else {
                                    pagecount = bean.getMap().getPageInfo().getTotal() / pageSize + 1;
                                }

                                if (pageNum > pagecount) {
                                    refreshLayout.finishLoadMoreWithNoMoreData();
                                } else {
                                    refreshLayout.setNoMoreData(false);
                                }
                            } else {
                                if (pageNum - 1 == 1) {
                                    empty.setVisibility(View.VISIBLE);
                                } else {
                                    empty.setVisibility(View.GONE);
                                }
//                                showToast(bean.getMsg());
                            }

                        } else {
                            if (pageNum - 1 == 1) {
                                empty.setVisibility(View.VISIBLE);
                            } else {
                                empty.setVisibility(View.GONE);
                            }
//                            showToast(bean.getMsg());
                        }
                        dismissDialog();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        dismissDialog();
                        if (pageNum - 1 == 1) {
                            empty.setVisibility(View.VISIBLE);
                        } else {
                            empty.setVisibility(View.GONE);
                        }
                    }
                });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNum = 1;
        initData();
    }


    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        initData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessage(String messageEvent) {
        if ("点赞成功".equals(messageEvent)) {
            pageNum = 1;
            initData();
        }
    }

    @Override
    @OnClick({R.id.empty})
    public void onViewClicked(View view) {
        super.onViewClicked(view);
        switch (view.getId()) {
            case R.id.empty:
                onRefresh(refreshLayout);
                break;
        }
    }
}
